package com.module.third.qiniu;

import android.media.MediaMetadataRetriever;
import android.text.TextUtils;

import androidx.annotation.IntRange;

import com.module.third.ThirdUtil;
import com.qiniu.android.common.FixedZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONObject;

import java.io.File;

public class QiniuUtils {

    public static class Listener {
        private volatile boolean isCancelled = false;

        public void onSuc(QiniuRerun qiniuRerun) {
        }

        public void onFail() {
        }


        public void progress(String key, double percent) {
        }

        public boolean isCancelled() {
            return isCancelled;
        }

        public void cancel() {
            isCancelled = true;
        }
    }

    public static Configuration getConfiguration() {
        Configuration config = new Configuration.Builder()
                .connectTimeout(90)              // 链接超时。默认90秒
                .useHttps(true)                  // 是否使用https上传域名
                .useConcurrentResumeUpload(true) // 使用并发上传，使用并发上传时，除最后一块大小不定外，其余每个块大小固定为4M，
                .concurrentTaskCount(3)          // 并发上传线程数量为3
                .responseTimeout(90)             // 服务器响应超时。默认90秒
//                .recorder(recorder)              // recorder分片上传时，已上传片记录器。默认null
//                .recorder(recorder, keyGen)      // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
                .zone(FixedZone.zone0)           // 设置区域，不指定会自动选择。指定不同区域的上传域名、备用域名、备用IP。
                .build();
        return config;
    }

    public static void upload(String filePath, long duration, String name, Listener listener) {
        String token = QiniuSignUtils.getUploadToken(filePath, duration, 1 * 60 * 60);
        UploadOptions options = new UploadOptions(null, null, false,
                new UpProgressHandler() {
                    public void progress(String key, double percent) {
                        //上次进度
                        if (listener != null) {
                            listener.progress(key, percent);
                        }
                    }
                },
                new UpCancellationSignal() {

                    @Override
                    public boolean isCancelled() {
                        if (listener != null) {
                            return listener.isCancelled();
                        } else {
                            return false;
                        }
                    }
                });

        UploadManager uploadManager = new UploadManager(getConfiguration());
        uploadManager.put(filePath, name, token, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                if (listener != null) {
                    if (info.isOK()) {
                        listener.onSuc(ThirdUtil.fromJson(response.toString(), QiniuRerun.class));
                    } else {
                        listener.onFail();
                    }
                }
            }
        }, options);
    }

    private static long getVideoDuration(String path) {
        long duration = 0; // 视频时长
        try {
            MediaMetadataRetriever retr = new MediaMetadataRetriever();
            retr.setDataSource(path);
            duration = Long.parseLong(retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return duration;
    }

    public static String getVideoCover(String url) {
        if (url == null) {
            return null;
        }
        if (!url.startsWith("http://" + QiniuSignUtils.HOST) && !url.startsWith("https://" + QiniuSignUtils.HOST)) {
            return url;
        }
        return url + "?vframe/jpg/offset/0";
    }

    /**
     * 指定视频封面宽高，会变形
     */
    public static String getVideoCover(String url, int width, int height) {
        if (url == null) {
            return null;
        }
        if (!url.startsWith("http://" + QiniuSignUtils.HOST) && !url.startsWith("https://" + QiniuSignUtils.HOST)) {
            return url;
        }
        return url + String.format("?vframe/jpg/offset/0/w/%d/h/%d", width, height);
    }

    public static String getVideoCover(String url, int width) {
        if (url == null) {
            return null;
        }
        if (!url.startsWith("http://" + QiniuSignUtils.HOST) && !url.startsWith("https://" + QiniuSignUtils.HOST)) {
            return url;
        }
        return url + String.format("?vframe/jpg/offset/0/w/%d", width);
    }

    public static String getUrl(String url, int width, int height) {
        if (url == null) {
            return null;
        }
        if (!url.startsWith("http://" + QiniuSignUtils.HOST) && !url.startsWith("https://" + QiniuSignUtils.HOST)) {
            return url;
        }
        return url + String.format("?imageView2/1/w/%d/h/%d", width, height);
    }

    /**
     * 好像无效，还是正方形
     */
    public static String getUrl(String url, int width) {
        if (url == null) {
            return null;
        }
        if (!url.startsWith("http://" + QiniuSignUtils.HOST) && !url.startsWith("https://" + QiniuSignUtils.HOST)) {
            return url;
        }
        return url + String.format("?imageView2/1/w/%d", width);
    }


    /**
     * 图片压缩
     */
    public static String getQualityUrl(String url, @IntRange(from = 1, to = 100) int quality) {
        if (url == null) {
            return null;
        }
        if (!url.startsWith("http://" + QiniuSignUtils.HOST) && !url.startsWith("https://" + QiniuSignUtils.HOST)) {
            return url;
        }
        return url + String.format("?imageView2/1/q/%d", quality);
    }

    /**
     * 图片压缩
     * 缩略图
     */
    public static String getThumbnail(String url) {
        return getQualityUrl(url, 10);
    }

    /**
     * 根据key 获取对应的url
     */
    public static String getKeyUrl(String key) {
        String url = null;
        if (!TextUtils.isEmpty(key)) {
            url = "http://" + QiniuSignUtils.HOST + File.separator + key;
        }
        return url;
    }

    /**
     * 根据url获取对应的key
     */
    public static String getKey(String url) {
        String key = null;
        if (!TextUtils.isEmpty(url)) {
            key = url.replace("http://" + QiniuSignUtils.HOST + File.separator, "");
        }
        return key;
    }
}
